﻿using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using RBAC.LuFang.API.Application.Command.UserCommand;
using RBAC.LuFang.API.Dtos;
using RBAC.LuFang.API.Extensions;
using RBAC.LuFang.Domain;
using RBAC.LuFang.Domain.DTO;
using RBAC.LuFang.Domin.Services;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace RBAC.LuFang.API.Controllers
{
    /// <summary>
    /// 用户控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]
    public class UsersController : ControllerBase
    {
        private readonly IUserService _IuserService;
        private readonly IMediator _mediator;
        private readonly IConfiguration configuration;
        //构造函数
        public UsersController(IUserService iuserService, IMediator mediator, IConfiguration configuration)
        {
            _IuserService = iuserService;
            _mediator = mediator;
            this.configuration = configuration;
        }
        /// <summary>
        /// 截取身份证上的年月日（调用扩展方法）
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<string> Get()
        {
            string aa = "371727200409140121";
            string aab = aa.Tosubstring();
            return aab;
        }

        /// <summary>
        /// 注册用户
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult<int>> AddUser(UserCreateCommand user)
        {
            ApiResult<int> result = new ApiResult<int>();
            try
            {
                result.Data = await _mediator.Send(user);
            }
            catch (Exception ee)
            {
                result.Code = -1;
                result.Message = ee.Message;
                throw;
            }
            return result;
        }
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="uname"></param>
        /// <param name="upwd"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<ApiResult<string>> GetLogin([FromQuery]UserLoginCommand user)
        {
            ApiResult<string> result = new ApiResult<string>();
            try
            {

                //result.Data = await _mediator.Send(user);
                var res = await _mediator.Send(user);
                if (res.code==1)
                {
                    result.Code = 1;
                    result.Data = JwtNewString(_mediator.Send(user).Result.uid.ToString(),res.rid);
                    result.Message = "登录成功";
                }
                else if (res.code == -1)
                {
                    result.Code = -1;
                    result.Message = "用户名不存在";
                }
                else if (res.code == -2)
                {
                    result.Code = -2;
                    result.Message = "密码错误";
                }
            }
            catch (Exception ee)
            {
                result.Code = -1;
                result.Message = ee.Message;
                throw;
            }
            return result;
        }
        /// <summary>
        /// 签发Token令牌
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        private string JwtNewString(string uid,string rid)
        {
            //生成JWT
            //Header,选择签名算法
            var signingAlogorithm = SecurityAlgorithms.HmacSha256;
            //Payload,存放用户信息，下面我们放了一个用户id
            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.Sub,uid),
                new Claim(ClaimTypes.Role,rid),
                new Claim(ClaimTypes.UserData,"测试")
            };
            //Signatrue
            //取出私钥并以utf8编码字节输出
            var secretByte = Encoding.UTF8.GetBytes(configuration["Authentication:SecreKey"]);
            //使用非对称算法对私钥进行加密
            var signingKey = new SymmetricSecurityKey(secretByte);
            //使用H麻城Sha6来验证加密后的私钥生成数字签名
            var signingCredentials = new SigningCredentials(signingKey, signingAlogorithm);
            //生成Token
            var ToKen = new JwtSecurityToken( 
                    issuer: configuration["Authentication:Issuer"], //发布者
                    audience: configuration["Authentication:Audience"],  //接收者
                    claims:claims,  //存放的用户信息
                    notBefore:DateTime.UtcNow,  //发布时间
                    expires:DateTime.UtcNow.AddDays(1), //有效期设置为1天
                    signingCredentials   //数字签名
                );

            //生成字符串Token
            var ToKenStr=new JwtSecurityTokenHandler().WriteToken(ToKen);
            return ToKenStr;

        }
        /// <summary>
        /// 显示省
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult<List<Province>>> GetProvince()
        {
            ApiResult<List<Province>> result = new ApiResult<List<Province>>();
            try
            {
                result.Data = await _mediator.Send(new ProvinceSelectCommand());
            }
            catch (Exception ee)
            {
                result.Code = -1;
                result.Message = ee.Message;
                throw;
            }
            return result;
        }
        /// <summary>
        /// 显示市
        /// </summary>
        /// <param name="pid"></param>
        /// <returns></returns>
        [HttpGet]
       
        public async Task<ApiResult<List<TheCity>>> GetTheCity([FromQuery]TheCitySelectCommand theCity)
        {
            ApiResult<List<TheCity>> result = new ApiResult<List<TheCity>>();
            try
            {
                result.Data = await _mediator.Send(theCity);
            }
            catch (Exception ee)
            {
                result.Code = -1;
                result.Message = ee.Message;
                throw;
            }
            return result;
        }
        /// <summary>
        /// 显示县
        /// </summary>
        /// <param name="thecityId"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult<List<County>>> GetCounty([FromQuery]CountySelectCommand county)
        {
            ApiResult<List<County>> result = new ApiResult<List<County>>();
            try
            {
                result.Data = await _mediator.Send(county);
            }
            catch (Exception ee)
            {
                result.Code = -1;
                result.Message = ee.Message;
                throw;
            }
            return result;
        }
        /// <summary>
        /// 显示用户列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult<page>> GetUser([FromQuery]UserSelectCommand user)
        {
            ApiResult<page> result = new ApiResult<page>();
            try
            {
                result.Data = await _mediator.Send(user);
            }
            catch (Exception ee)
            {
                result.Code = -1;
                result.Message = ee.Message;
                throw;
            }
            return result;
        }
        /// <summary>
        /// 用户反填
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult<UserInfo>> GetByid([FromQuery]UserFanCommand userFan)
        {
            ApiResult<UserInfo> result=new ApiResult<UserInfo>();
            try
            {
                result.Data=await _mediator.Send(userFan);
            }
            catch (Exception ee)
            {
                result.Code = -1;
                result.Message = ee.Message;
                throw;
            }
            return result;
        }
        /// <summary>
        /// 修改用户
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<ApiResult<int>> UpdUser(UserUpdateCommand user)
        {
            ApiResult<int> result = new ApiResult<int>();
            try
            {
                result.Data=await _mediator.Send(user);
            }
            catch (Exception ee)
            {
                result.Code = -1;
                result.Message = ee.Message;
                throw;
            }
            return result;
        }
        /// <summary>
        /// 用户删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpPut]
        public async Task<ApiResult<int>> DelUser([FromQuery]UserDeleteCommand userDelete)
        {
            ApiResult<int> result= new ApiResult<int>();
            try
            {
                result.Data = await _mediator.Send(userDelete);
            }
            catch (Exception ex)
            {
                result.Code = -1;
                result.Message = ex.Message;
                throw;
            }
            return result;
        }
        /// <summary>
        /// 获取用户反填请假
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpGet]
        public async Task<UserInfo> GetUserFanJWT()
        {
            try
            {
                var id = Convert.ToInt32(HttpContext.User.FindFirst(ClaimTypes.NameIdentifier)?.Value);
                return await _IuserService.GetByid(id);
            }
            catch (Exception)
            {

                throw;
            }
        }








    }
}
